import com.alibaba.fastjson.JSONObject;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * 极光认证服务端Demo
 */
public class Jverification_Test {

    /**
     * 极光提交loginToken接口地址
     */
    private static String loginTokenVerify_url = "https://api.verification.jpush.cn/v1/web/loginTokenVerify";

    /**
     * RSA私钥 http://web.chacuo.net/netrsakeypair 不需要证书密码
     */
    private static String prikey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMfCYKta5ZBQ+hofYDyu51Ul6vngX56hK86KdXTXujeDUJiMqt9mAxYwGoMSeDDeN1aBEecn8QN5LTOtyf9b8pkPEkFs5aqG8wVjE80uIWsxEMuMmb9+n4kgDneNPgrBW8l2jvsSsXWF3LDUwTMS2kI10V5f3sQNeLKBF8fjR++XAgMBAAECgYAFgTfEwRZ+aZzax26RfYhmcksNY79+0ZYxdONTuvYovXelHItA6MDBBcZVQlcJkbYYrineIt2jaN10BSAB53jB7ohOhAhg4ucl2YiiOBC1zZAwCg4BDR3vfWkeF2TE/gRPf9WgTow8kP+qLeZw5CQrp6NMKUq1nDwJ5C6WtNYGwQJBAPIYP0ZC3vCXitl3tjCojihmSNwvXBjK8gF4zaxSdGhWxlpUmaoFTGds9RUQ4MV4TEOQrP6mCfDno+BCYwr4TwcCQQDTO6G2huHNWfRYfuymTltvk+MLaaodHV0YQvPMq3YzabkYqqBSMvLLnzG/CKlBCqv65/xscCo+WlLrnABIwabxAkBj5bN+Z6uc9bt63xYT4AnBC+v2x6gmJuBT0Sh1ehTE1UHGFnDOIp+TcfdzuOI3OdumabWo4pTpjnwl1t8NsMbTAkEAhjNbkWBucw3UjKjO5vXfZ6sYU3blSiwOqkxXIlBI/28K1t4Ij1CpKq7QZyM0jQsfqn/awnYckJLIHcJ198N4sQJAHK60A+VksPGDb7MthwKrAjhwtQwW1Fch2f1MGbCpGcrtmQqu6XlQOR8+Vdpv1DWCX6YQMBOmqz7lbLHM2T6glA==";

    /**
     * 极光后台应用设置里面的appkey
     */
    private static String appKey = "41f3e34b401752a63dbc27cc";

    /**
     * 极光后台应用设置里面的masterSecret
     */
    private static String masterSecret = "b4dc0fafcced7d1a20a9d092";

    public static void main(String[] args) throws Exception {
        // 从客户端获取到的loginToken
        String loginToken = "H0/H4x3AfOfK4MsQHZZPdfP4Y8+0fX1E+506nVXiL6gdBrMXv4L32aCrQCXo+tyOZOL2DEKfTpE4ccDKJwqLPFzW9opTmY+FSSMFz1l5Z1EfNm8wz6eW+QA5CkFglkzu2eoq2MqMWJJYu/aetYSIw4wcl2xcsQxaulAvhj6ILDm2i5lcSa0K4eiovyOLZ31a0v/no5SQGwp2CGnalwhFU6rzURF26iE+STJEVpIC77Ob88lqmyL1PAkQ2WUc/4fB4DfK5SB9McXHeT4GBdAR+TWgMWJ8AODmIpmahOZ4blfetbHfDYaBRhz/l27Jc6oLsqKkqnOG5VNGlae2ANMCmHe/SxZAdjRhSWH/1EH8SRJ8M7qnT1+uqywGMFjHCY9T";
        // 第一步 先将客户端获取到的loginToken提交到极光
        JSONObject loginTokenVerify_json = sendLoginTokenVerify(loginToken);

        // 第二步 解密手机号
        String cryptograph = loginTokenVerify_json.getString("phone");
        String phone = decrypt(cryptograph);
        System.out.println(phone);
    }

    /**
     * 提交loginToken 换取加密手机号
     * @param loginToken
     * @return
     */
    public static JSONObject sendLoginTokenVerify(String loginToken) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("loginToken", loginToken);
        jsonObject.put("exID", "123");
        // 重点注意：头部需要添加鉴权信息,务必按照下述格式处理，文档说明：https://docs.jiguang.cn//jverification/server/rest_api/rest_api_summary/
        String authorization = "Basic " + base64(appKey + ":" + masterSecret);
        String result = HttpUtils.sendPost(loginTokenVerify_url, jsonObject.toString(), authorization);
        JSONObject result_json = JSONObject.parseObject(result);
        if (result_json.getInteger("code") == 8000) {
            return result_json;
        } else {
            throw new Exception("错误：" + result_json.toJSONString() + "\n 错误码对应链接：https://www.yuque.com/docs/share/1f20bd56-00db-424d-9f36-067e774ad2bd?# 《认证服务端常见错误码总结》");
        }
    }

    /**
     * base64加密鉴权信息
     * @param str
     * @return
     */
    public static String base64(String str) {
        byte[] bytes = str.getBytes();

        //Base64 加密
        String encoded = Base64.getEncoder().encodeToString(bytes);

        return encoded;
    }

    final static Base64.Decoder decoder = Base64.getDecoder();
    /**
     * 解密加密手机号
     * @param cryptograph 加密手机号
     * @return
     * @throws Exception
     */
    public static String decrypt(String cryptograph) throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(prikey));
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);

        // Android原生解密需要修改Cipher.getInstance(“RSA/ECB/PKCS1Padding”);
        Cipher cipher= Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte [] b = decoder.decode(cryptograph.getBytes("UTF-8"));
        return new String(cipher.doFinal(b));
    }
}
